package cn.edu.gingkoc.simpleems;

import cn.edu.gingkoc.simpleems.control.EmployeeManagement;
import cn.edu.gingkoc.simpleems.model.Employee;

import java.util.List;
import java.util.Scanner;
import java.util.regex.Pattern;

public class SimpleEms {
    private static final int EMPLOYEE_INFO_LENGTH = 5;
    private static final int ID_INDEX = 0;
    private static final int NAME_INDEX = 1;
    private static final int SEX_INDEX = 2;
    private static final int AGE_INDEX = 3;
    private static final int SALARY_INDEX = 4;

    /**
     * 主函数
     * ...
     *
     * @param args
     */
    public static void main(String[] args) {
        EmployeeManagement employeeManagement = new EmployeeManagement();
        Scanner scanner = new Scanner(System.in);
        try {
            do {
                printMenu();
                if (scanner.hasNext()) {
                    String choiceString = scanner.nextLine();
                    if (!isNumeric(choiceString)) {
                        System.out.println("【SEMS】：请输入0-5数字菜单");
                        continue;
                    }
                    switch (choiceString) {
                        case "1":
                            System.out.println("请输入需要添加的员工的5项信息：" +
                                    "工号（整数）、姓名、性别（Female或Male）、年龄（整数）、工资（整数），以空格隔开：");
                            String inputInfo = scanner.nextLine().replaceAll("\\s+", " ");
                            if (isValidEmployeeInfo(inputInfo)) {
                                employeeManagement.add(parseEmployee(inputInfo));
                            }
                            break;
                        case "2":
                            System.out.println("请输入需要删除的员工工号：");
                            String employeeIDString = scanner.nextLine();
                            if (!isNumeric(employeeIDString)) {
                                System.out.println("【SEMS】输入无效，员工工号必须是整数");
                                break;
                            }
                            employeeManagement.delete(Integer.parseInt(employeeIDString));
                            break;
                        case "3":
                            System.out.println("请输入需要修改的员工的5项信息：" +
                                    "工号（整数）、姓名、性别（Female或Male）、年龄（整数）、工资（整数），以空格隔开：");
                            String modificationInfo = scanner.nextLine().replaceAll("\\s+", " ");
                            if (isValidEmployeeInfo(modificationInfo)) {
                                employeeManagement.modify(parseEmployee(modificationInfo));
                            }
                            break;
                        case "4":
                            System.out.println("请输入需要查询的员工工号：");
                            String employeeIDString2 = scanner.nextLine();
                            if (!isNumeric(employeeIDString2)) {
                                System.out.println("【SEMS】输入无效，员工工号必须是整数");
                                break;
                            }
                            printOneEmployeesInfo(employeeManagement, Integer.parseInt(employeeIDString2));
                            break;
                        case "5":
                            printAllEmployeesInfo(employeeManagement.getAllEmployees());
                            break;
                        case "0":
                            System.exit(0);
                        default:
                            break;
                    }
                }
            } while (true);
        } finally {
            if (scanner != null) {
                scanner.close();
            }
        }
    }

    private static Employee parseEmployee(final String modificationInfo) {
        String[] splittedInfo = modificationInfo.trim().split(" ");
        return new Employee(Integer.parseInt(splittedInfo[ID_INDEX]), splittedInfo[NAME_INDEX], splittedInfo[SEX_INDEX].toLowerCase(), Integer.parseInt(splittedInfo[AGE_INDEX]), Integer.parseInt(splittedInfo[SALARY_INDEX]));
    }

    private static void printMenu() {
        System.out.println("-----------------员工管理系统-----------------");
        System.out.println("1.添加员工信息");
        System.out.println("2.删除员工信息");
        System.out.println("3.修改员工信息");
        System.out.println("4.查询员工信息");
        System.out.println("5.显示所有员工信息");
        System.out.println("0.退出程序");
        System.out.println("--------------------------------------------");
        System.out.println("请输入您的选择：");
    }

    private static boolean isValidEmployeeInfo(final String inputInfo) {
        String[] splittedInfo = inputInfo.trim().split(" ");
        if (splittedInfo == null || splittedInfo.length != EMPLOYEE_INFO_LENGTH) {
            System.out.println("【SEMS】：输入信息不是5项");
            return false;
        }
        //工号、年龄、工资输入的不是数字
        if (!isNumeric(splittedInfo[ID_INDEX]) || !isNumeric(splittedInfo[AGE_INDEX]) || !isNumeric(splittedInfo[SALARY_INDEX])) {
            System.out.println("【SEMS】：输入信息有误，员工ID、年龄或工资非整数");
            return false;
        }
        //性别输入的不是“male”或“female”
        if (isInvalidSexInfo(splittedInfo)) {
            System.out.println("【SEMS】：输入信息有误，员工性别不是male或female");
            return false;
        }
        return true;
    }

    private static boolean isInvalidSexInfo(final String[] splittedInfo) {
        String sexInLowerCase = splittedInfo[2].toLowerCase();
        return !sexInLowerCase.equals("male") && !sexInLowerCase.equals("female");
    }

    /**
     * 判断字符串是否是数字
     * ...
     *
     * @param string
     * @return 字符串是否是数字
     */
    public static boolean isNumeric(final String string) {
        Pattern pattern = Pattern.compile("[0-9]*");
        return pattern.matcher(string).matches();
    }

    private static void printOneEmployeesInfo(final EmployeeManagement employeeManagement, final int id) {
        Employee employeeFound = employeeManagement.getEmployeeByID(id);
        if (employeeFound == null) {
            System.out.println(String.format("【SEMS】：工号为[%s]的员工在系统中不存在", id));
            return;
        }
        StringBuilder stringBuilder = getEmployeeInfoHeading();
        stringBuilder.append(employeeFound);
        System.out.println(stringBuilder);
    }

    private static void printAllEmployeesInfo(final List<Employee> employees) {
        if (employees == null || employees.isEmpty()) {
            System.out.println("【SEMS】：当前系统中无员工记录！");
            return;
        }
        StringBuilder stringBuilder = getEmployeeInfoHeading();
        employees.forEach(employee -> {
            stringBuilder.append(employee);
        });
        System.out.println(stringBuilder);
    }

    private static StringBuilder getEmployeeInfoHeading() {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("===============员工信息===================\n");
        stringBuilder.append("工号      姓名      性别      年龄      工资\n");
        return stringBuilder;
    }
}
